package com.waypolice.manager.controller;

import com.waypolice.base.BaseController;
import com.waypolice.common.constant.BorrowConstant;
import com.waypolice.common.constant.CmsResult;
import com.waypolice.common.pojo.SearchResult;
import com.waypolice.common.pojo.TaotaoResult;
import com.waypolice.common.utils.DateTimeUtil;
import com.waypolice.common.utils.FastDfsClient;
import com.waypolice.common.utils.PageUtils;
import com.waypolice.manager.service.*;
import com.waypolice.pojo.*;
import com.waypolice.pojo.vo.Variable;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.identity.User;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.StringReader;
import java.util.*;


/**
 * 档案检索
 * @author zry
 *
 */
@Controller
@Api(value = "档案", description = "档案检索")
@RequestMapping(value="/pcwindow")
public class ArcSearchAction extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ArcSearchAction.class);

	@Value("${IMAGE_SERVER_URL}")
	private String IMAGE_SERVER_URL;
	@Autowired
	private ArcCreateService arcCreateService;
	@Autowired
	private VolAndItemService volAndItemService;
	@Autowired
	private ArcSearchService arcSearchService;
	@Autowired
	protected UserService userService;
	@Autowired
	private ActDefineService actDefineService;
	@Autowired
	private BorRegisterService borRegisterService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	protected RuntimeService runtimeService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	private BorAuditService borAuditService;
	@Autowired
	private UpmsUserRoleService upmsUserRoleService;
	@Autowired
	public UpmsDictionaryService upmsDictionaryService;

	/**
	 * 档案著录页面跳转
	 *
	 * @param map
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/searchArc")
	public String userManagerJump(ModelMap map, HttpServletResponse response,
								  HttpServletRequest request) {
		return "/searchArchive/searchArc";
	}
	@RequestMapping(value = "/searchArcAll")
	public String searchAllJump(ModelMap map, HttpServletResponse response,
								  HttpServletRequest request) {
		return "/searchArchive/searchAll";
	}
	@RequestMapping(value = "/searchApply")
	public String searchApplyJump(ModelMap map, HttpServletResponse response,
								  HttpServletRequest request) {
		return "/searchArchive/searchApply";
	}
	@RequiresPermissions("cms:search:searchApply")
	@RequestMapping(value = "/searchManager")
	public String searchManagerJump(ModelMap map, HttpServletResponse response,
								  HttpServletRequest request) {
		return "/searchArchive/searchManager";
	}

	@ApiOperation(value = "根据条件查询卷")
	@RequestMapping(value = "/searchJudMessage", method = RequestMethod.GET)
	@ResponseBody
	public Object searchVolume(
			@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
			@RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
			@RequestParam(required = false, value = "sort") String sort,
			@RequestParam(required = false, value = "order") String order,
			@RequestParam(required = false, value = "searchmodelTwo") String searchmodelTwo) {
		List<CmsJudVolume> list = new ArrayList<CmsJudVolume>();
		List<CmsJudVolume> volumes = new ArrayList<CmsJudVolume>();
		list = com.alibaba.fastjson.JSONObject.parseArray(searchmodelTwo, CmsJudVolume.class);
		if(list.size()!=1){
			return null;
		}
		//判断当前用户是否为档案管理员
		TaotaoResult result1 = selectUserIsManager();
		if(result1.getStatus() == 200){
			//是档案管理员，查询所有档案
			 volumes = arcSearchService.findAllVolumeByAll(list);
		}else{
			//不是是档案管理员，判断检索范围
			List<UpmsDictionary> types = upmsDictionaryService.findAllSearchScope();
			if (!types.isEmpty()) {
				String scope = "";
				for (UpmsDictionary type : types) {
					if("1".equals(type.getStr2())){
						if(type.getCode().equals("search-public")){
							scope = "1";
						}else{
							scope = "2";
						}
					}
				}
				if("".equals(scope)){
					//全部检索
					volumes = arcSearchService.findAllVolumeByAll(list);
				}else if("1".equals(scope)){
					//按公开检索
					volumes = arcSearchService.findAllVolume(list,1);
				}else{
					//按涉密检索
					volumes = arcSearchService.findAllVolume(list,2);
				}
			}
		}
		Map<String, Object> result = new HashMap<>(2);
		//最终的list集合,分页操作
		List<CmsJudVolume> finalList = new ArrayList<CmsJudVolume>();
		PageUtils<CmsJudVolume> pageUtils = new PageUtils<CmsJudVolume>();
		finalList = pageUtils.pageList(volumes,offset,limit);
		result.put("rows",finalList);
		result.put("total",volumes.size());
		return result;
	}
	@ApiOperation(value = "根据条件查询件")
	@RequestMapping(value = "/searchItemMessage", method = RequestMethod.GET)
	@ResponseBody
	public Object searchItem(
			@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
			@RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
			@RequestParam(required = false, value = "sort") String sort,
			@RequestParam(required = false, value = "order") String order,
			@RequestParam(required = false, value = "searchmodelOne") String searchmodelOne) {
		List<CmsJudItem> list = new ArrayList<CmsJudItem>();
		list = com.alibaba.fastjson.JSONObject.parseArray(searchmodelOne, CmsJudItem.class);
		if(list.size()!=1){
			return null;
		}
		List<CmsJudItem> items = arcSearchService.findAllItem(list);
		Map<String, Object> result = new HashMap<>(2);
		//最终的list集合,分页操作
		List<CmsJudItem> finalList = new ArrayList<CmsJudItem>();
		PageUtils<CmsJudItem> pageUtils = new PageUtils<CmsJudItem>();
		finalList = pageUtils.pageList(items,offset,limit);
		result.put("rows",finalList);
		result.put("total",items.size());
		return result;
	}
	@ApiOperation(value = "根据条件查询单件")
	@RequestMapping(value = "/searchItemSinMessage", method = RequestMethod.GET)
	@ResponseBody
	public Object searchSinItem(
			@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
			@RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
			@RequestParam(required = false, value = "sort") String sort,
			@RequestParam(required = false, value = "order") String order,
			@RequestParam(required = false, value = "searchmodelThree") String searchmodelThree) {
		List<CmsSinItem> list = new ArrayList<CmsSinItem>();
		List<CmsSinItem> sinItems = new ArrayList<CmsSinItem>();
		list = com.alibaba.fastjson.JSONObject.parseArray(searchmodelThree, CmsSinItem.class);
		if(list.size()!=1){
			return null;
		}
		//判断当前用户是否为档案管理员
		TaotaoResult result1 = selectUserIsManager();
		if(result1.getStatus() == 200){
			//是档案管理员，查询所有档案
			sinItems = arcSearchService.findAllSinItemAll(list);
		}else{
			//不是是档案管理员，判断检索范围
			List<UpmsDictionary> types = upmsDictionaryService.findAllSearchScope();
			if (!types.isEmpty()) {
				String scope = "";
				for (UpmsDictionary type : types) {
					if("1".equals(type.getStr2())){
						if(type.getCode().equals("search-public")){
							scope = "1";
						}else{
							scope = "2";
						}
					}
				}
				if("".equals(scope)){
					//全部检索
					sinItems = arcSearchService.findAllSinItemAll(list);
				}else if("1".equals(scope)){
					//按公开检索
					sinItems = arcSearchService.findAllSinItem(list,1);
				}else{
					//按涉密检索
					sinItems = arcSearchService.findAllSinItem(list,2);
				}
			}
		}
		Map<String, Object> result = new HashMap<>(2);
		//最终的list集合,分页操作
		List<CmsSinItem> finalList = new ArrayList<CmsSinItem>();
		PageUtils<CmsSinItem> pageUtils = new PageUtils<CmsSinItem>();
		finalList = pageUtils.pageList(sinItems,offset,limit);
		result.put("rows",finalList);
		result.put("total",sinItems.size());
		return result;
	}
	@ApiOperation(value = "根据条件查询卷内件")
	@RequestMapping(value = "/searchAllMessage", method = RequestMethod.GET)
	@ResponseBody
	public Object searchAllMessage(
			@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
			@RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
			@RequestParam(required = false, value = "sort") String sort,
			@RequestParam(required = false, value = "order") String order,
			@RequestParam(required = false, value = "searchmodelOne") String searchmodelOne,
			@RequestParam(required = false, value = "searchmodelTwo") String searchmodelTwo) {
		List<CmsJudVolume> vollist = new ArrayList<CmsJudVolume>();
		List<CmsJudItem> itemlist = new ArrayList<CmsJudItem>();
		List<CmsJudItem> items = new ArrayList<CmsJudItem>();
		vollist = com.alibaba.fastjson.JSONObject.parseArray(searchmodelTwo, CmsJudVolume.class);
		itemlist = com.alibaba.fastjson.JSONObject.parseArray(searchmodelOne, CmsJudItem.class);
		if(vollist.size()!=1 || itemlist.size()!=1){
			return null;
		}
		//判断当前用户是否为档案管理员
		TaotaoResult result1 = selectUserIsManager();
		if(result1.getStatus() == 200){
			//是档案管理员，查询所有档案
			items = arcSearchService.findAllItemAll(vollist,itemlist);
		}else{
			//不是是档案管理员，判断检索范围
			List<UpmsDictionary> types = upmsDictionaryService.findAllSearchScope();
			if (!types.isEmpty()) {
				String scope = "";
				for (UpmsDictionary type : types) {
					if("1".equals(type.getStr2())){
						if(type.getCode().equals("search-public")){
							scope = "1";
						}else{
							scope = "2";
						}
					}
				}
				if("".equals(scope)){
					//全部检索
					items = arcSearchService.findAllItemAll(vollist,itemlist);
				}else if("1".equals(scope)){
					//按公开检索
					items = arcSearchService.findAllVolumeAndItem(vollist,itemlist,1);
				}else{
					//按涉密检索
					items = arcSearchService.findAllVolumeAndItem(vollist,itemlist,2);
				}
			}
		}
		Map<String, Object> result = new HashMap<>(2);
		//最终的list集合,分页操作
		List<CmsJudItem> finalList = new ArrayList<CmsJudItem>();
		PageUtils<CmsJudItem> pageUtils = new PageUtils<CmsJudItem>();
		finalList = pageUtils.pageList(items,offset,limit);
		result.put("rows",finalList);
		result.put("total",items.size());
		return result;
	}
	@ApiOperation(value = "根据条件查询卷件----暂停使用")
	@RequestMapping(value = "/searchItemAndArchive111111")
	@ResponseBody
	public Object searchItemAndArchive111111(HttpServletRequest request, HttpServletResponse response) throws IOException {
		SearchResult newSearchResult = new SearchResult();
		TaotaoResult result1 = selectUserIsManager();
		String Message = request.getParameter("arcSearchMessage");
		//独立Lucene实现
		StringReader re = new StringReader(Message);
		IKSegmenter ik = new IKSegmenter(re,true);
		Lexeme lex = null;
		String arcSearchMessage = null;
		int searchItemNumber = 0;
		int searchVolNumber = 0;
		int searchSinItemNum = 0;
		List<CmsJudVolume> newVolList = new ArrayList<>();
		List<CmsJudItem> newItemlist = new ArrayList<>();
		List<CmsSinItem> newSinItemlist = new ArrayList<>();
		while((lex=ik.next())!=null){
			SearchResult searchResult = new SearchResult();
			arcSearchMessage = lex.getLexemeText();
			if(result1.getStatus() == 200){
				searchResult = arcSearchService.findAllVolumeAndItemByQwAll(arcSearchMessage);
			}else {
				//不是档案管理员，判断检索范围
				List<UpmsDictionary> types = upmsDictionaryService.findAllSearchScope();
				if (!types.isEmpty()) {
					String scope = "";
					for (UpmsDictionary type : types) {
						if ("1".equals(type.getStr2())) {
							if (type.getCode().equals("search-public")) {
								scope = "1";
							} else {
								scope = "2";
							}
						}
					}
					if ("".equals(scope)) {
						//全部检索
						searchResult = arcSearchService.findAllVolumeAndItemByQwAll(arcSearchMessage);
					} else if ("1".equals(scope)) {
						//按公开检索
						searchResult = arcSearchService.findAllVolumeAndItemByQw(arcSearchMessage, 1);
					} else {
						//按涉密检索
						searchResult = arcSearchService.findAllVolumeAndItemByQw(arcSearchMessage, 2);
					}
				}
			}
			if(searchResult != null){
				if(searchResult.getVollist() != null){
					List<CmsJudVolume> volList = searchResult.getVollist();
					if(!volList.isEmpty()){
						for (CmsJudVolume cmsJudVolume:volList) {
							newVolList.add(cmsJudVolume);
						}
					}
				}
				if(searchResult.getItemlist() != null){
					List<CmsJudItem> itemlist = searchResult.getItemlist();
					if(!itemlist.isEmpty()|| itemlist != null){
						for (CmsJudItem cmsJudItem:itemlist) {
							newItemlist.add(cmsJudItem);
						}
					}
				}
				if(searchResult.getSinItemlist() != null){
					List<CmsSinItem> sinItemlist = searchResult.getSinItemlist();
					if(!sinItemlist.isEmpty()|| sinItemlist != null){
						for (CmsSinItem cmsSinItem:sinItemlist) {
							newSinItemlist.add(cmsSinItem);
						}
					}
				}
			}
			searchItemNumber += searchResult.getSearchItemNum();
			searchVolNumber += searchResult.getSearchVolNum();
			searchSinItemNum += searchResult.getSearchSinItemNum();
		}
		newSearchResult.setVollist(newVolList);
		newSearchResult.setItemlist(newItemlist);
		newSearchResult.setSinItemlist(newSinItemlist);
		newSearchResult.setSearchVolNum(searchVolNumber);
		newSearchResult.setSearchItemNum(searchItemNumber);
		newSearchResult.setSearchSinItemNum(searchSinItemNum);
		return  newSearchResult;
	}
	@ApiOperation(value = "根据条件查询卷件")
	@RequestMapping(value = "/searchItemAndArchive")
	@ResponseBody
	public Object searchItemAndArchive(HttpServletRequest request, HttpServletResponse response) throws IOException {
		SearchResult newSearchResult = new SearchResult();
		TaotaoResult result1 = selectUserIsManager();
		String arcSearchMessage = request.getParameter("arcSearchMessage");
		if(StringUtils.isBlank(arcSearchMessage)){
			return null;
		}
		int searchItemNumber = 0;
		int searchVolNumber = 0;
		int searchSinItemNum = 0;
		List<CmsJudVolume> newVolList = new ArrayList<>();
		List<CmsJudItem> newItemlist = new ArrayList<>();
		List<CmsSinItem> newSinItemlist = new ArrayList<>();
				SearchResult searchResult = new SearchResult();
				if(result1.getStatus() == 200){
					searchResult = arcSearchService.findAllVolumeAndItemByQwAll(arcSearchMessage);
				}else {
					//不是档案管理员，判断检索范围
					List<UpmsDictionary> types = upmsDictionaryService.findAllSearchScope();
					if (!types.isEmpty()) {
						String scope = "";
						for (UpmsDictionary type : types) {
							if ("1".equals(type.getStr2())) {
								if (type.getCode().equals("search-public")) {
									scope = "1";
								} else {
									scope = "2";
								}
							}
						}
						if ("".equals(scope)) {
							//全部检索
							searchResult = arcSearchService.findAllVolumeAndItemByQwAll(arcSearchMessage);
						} else if ("1".equals(scope)) {
							//按公开检索
							searchResult = arcSearchService.findAllVolumeAndItemByQw(arcSearchMessage, 1);
						} else {
							//按涉密检索
							searchResult = arcSearchService.findAllVolumeAndItemByQw(arcSearchMessage, 2);
						}
					}
				}
				if(searchResult != null){
					if(searchResult.getVollist() != null){
						List<CmsJudVolume> volList = searchResult.getVollist();
						if(!volList.isEmpty()){
							for (CmsJudVolume cmsJudVolume:volList) {
								newVolList.add(cmsJudVolume);
							}
						}
					}
					if(searchResult.getItemlist() != null){
						List<CmsJudItem> itemlist = searchResult.getItemlist();
						if(!itemlist.isEmpty()|| itemlist != null){
							for (CmsJudItem cmsJudItem:itemlist) {
								newItemlist.add(cmsJudItem);
							}
						}
					}
					if(searchResult.getSinItemlist() != null){
						List<CmsSinItem> sinItemlist = searchResult.getSinItemlist();
						if(!sinItemlist.isEmpty()|| sinItemlist != null){
							for (CmsSinItem cmsSinItem:sinItemlist) {
								newSinItemlist.add(cmsSinItem);
							}
						}
					}
				searchItemNumber += searchResult.getSearchItemNum();
				searchVolNumber += searchResult.getSearchVolNum();
				searchSinItemNum += searchResult.getSearchSinItemNum();
			}
		newSearchResult.setVollist(newVolList);
		newSearchResult.setItemlist(newItemlist);
		newSearchResult.setSinItemlist(newSinItemlist);
		newSearchResult.setSearchVolNum(searchVolNumber);
		newSearchResult.setSearchItemNum(searchItemNumber);
		newSearchResult.setSearchSinItemNum(searchSinItemNum);
        return  newSearchResult;
	}
	@ApiOperation(value = "卷内件列表,排序页面")
	@RequestMapping(value = "/itemAndVolumeByVolId")
	@ResponseBody
	public Object itemAndVolumeByVolId(	@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
										   @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
										   @RequestParam(required = false, value = "sort") String sort,
										   @RequestParam(required = false, value = "order") String order,
										   @RequestParam(required = false, value = "volId") long volId) {
		List<CmsJudItem> rows = arcSearchService.selectItemAndVolumeByVolId(volId);
		Map<String, Object> result = new HashMap<>(2);
		//最终的list集合,分页操作
		List<CmsJudItem> finalList = new ArrayList<CmsJudItem>();
		PageUtils<CmsJudItem> pageUtils = new PageUtils<CmsJudItem>();
		finalList = pageUtils.pageList(rows,offset,limit);
		result.put("rows",finalList);
		result.put("total",rows.size());
		return result;
	}
	/**
	 * @author:zry
	 * @description 发送检索申请
	 */
	@ApiOperation("发送检索申请")
	@RequiresPermissions("cms:search:apply")
	@RequestMapping(value = "/sendSearchAct")
	@ResponseBody
	public Object sendSearchAct(MultipartFile file, HttpServletRequest request) throws Exception {
		CmsBorRegister cmsBorRegister=new CmsBorRegister();
		/* 获取前台数据信息*/
		String auditDept = request.getParameter("auditDept");
		Date planReturnTime = DateTimeUtil.strToDate(request.getParameter("planReturnTime"));
		String auditDetail = request.getParameter("auditDetail");
		String auditReason = request.getParameter("auditReason");
		//当动态制定时应用
		String userName = request.getParameter("userName");
		String delegateUser = request.getParameter("delegateUser");

		//获取当前登录人的账号
		Subject subject = SecurityUtils.getSubject();
		String username = (String) subject.getPrincipal();
		List<UpmsUser> users = userService.findByName(username);
		UpmsUser user = new UpmsUser();
		if(users!=null&&users.size()>0){
			user = users.get(0);
		}
		cmsBorRegister.setBorUserId((long)user.getUserId());
		cmsBorRegister.setPlanReturnTime(planReturnTime);
		cmsBorRegister.setBorPurpose(auditReason);
		cmsBorRegister.setExtend1(auditDetail);
		cmsBorRegister.setCreateTime(new Date());
		//暂时未有组织部门
		if(file!=null){
			// 取扩展名
			String originalFilename = file.getOriginalFilename();
			String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
			// 上传到图片服务器
			FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
			String fastDfSUrl = fastDFSClient.uploadFile(file.getBytes(),extName);
			String imagesUrl = IMAGE_SERVER_URL + fastDfSUrl;
			cmsBorRegister.setBorDeptDescription(auditDept);
			cmsBorRegister.setBorAttestUrl(imagesUrl);
		}else{
			cmsBorRegister.setBorDeptId(Long.parseLong(auditDept));
		}
		//获取当前借阅的最新的流程
		UpmsActDefine upmsActDefine = actDefineService.getNewAct("searchAct");
		if(upmsActDefine==null){
			return new CmsResult(0,"检索失败，请找系统管理员确认流程是否定义",0);
		}

		//获取流程的唯一标识
		String key = upmsActDefine.getAdKey();
		cmsBorRegister.setCreateTime(new Date());
		cmsBorRegister.setTaskType(BorrowConstant.AUDIT_TYPE_SEARCH);
		//开始时生成登记号 并且插入
		String finalRegist = borRegisterService.producePolicyNum(cmsBorRegister);
		cmsBorRegister.setRegisterNum(finalRegist);
		long cmsBorRegisterId = borRegisterService.insertSelectId(cmsBorRegister);
		//获取登记表的主键，记录其中
		String businessKey = String.valueOf(cmsBorRegisterId);

		ProcessInstance processInstance = null;
		Map<String, Object> variables = new HashMap<String, Object>();
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		//查找该登录人账户所登录的账户对应的用户id
		User nameUser = identityService.createUserQuery().userId(String.valueOf(user.getUserId())).singleResult();
		if(nameUser==null){
			identityService.setAuthenticatedUserId(user.getUsername());
		}else{
			identityService.setAuthenticatedUserId(String.valueOf(nameUser.getId()));
		}

		//如果流程具有 指定表达式，则替换改表达式
		if(StringUtils.isNotBlank(delegateUser)){
			variables.put(delegateUser,userName);
		}
		processInstance = runtimeService.startProcessInstanceByKey(key, businessKey, variables);
		String processInstanceId = processInstance.getId();
		//若启动的流程id存在，则启动成功
		if(processInstanceId!=null&&!"".equals(processInstanceId)){
			//若启动成功，则将其审核的流程记录在案
			CmsBorAuditing cmsBorAuditing = new CmsBorAuditing();
			//修改时间
			Date now = DateTimeUtil.getNow();
			cmsBorAuditing.setCreateTime(now);
			cmsBorAuditing.setBorRegisterId(cmsBorRegisterId);
			cmsBorAuditing.setAuditUserId((long)user.getUserId());
			cmsBorAuditing.setAuditType((long)BorrowConstant.AUDIT_TYPE_SEARCH);
			cmsBorAuditing.setAuditUserView("发起检索流程");
			cmsBorAuditing.setAuditIndex(System.currentTimeMillis()/1000);
			borAuditService.insert(cmsBorAuditing);
			return new CmsResult(1,"检索申请成功",0);
		}else{
			return new CmsResult(0,"检索申请失败，请稍后再试！",0);
		}
	}

	@ApiOperation(value = "查询当前登录用户角色是否为档案管理员")
	@RequestMapping(value = "/selectLoginUserRole")
	@ResponseBody
	public TaotaoResult selectLoginUserRole(HttpServletRequest request, HttpServletResponse response)  {
		TaotaoResult result = selectUserIsManager();
		return result;
	}

	/**
	 * @author:zyp
	 * @description 重新发起检索申请
	 * @date: 2019/3/25 11:34
	 * @return
	 */
	@ApiOperation(value = "重新发起检索申请")
	@RequestMapping(value = "/modifySearchAudit")
	@ResponseBody
	public Object modifySearchAudit(HttpServletRequest request){
		//获取参数
		String taskId = request.getParameter("taskId");
		String keys = request.getParameter("keys");
		String values = request.getParameter("values");
		String types = request.getParameter("types");
		String taskType = request.getParameter("taskType");
		Variable var = new Variable(keys,values,types);
		CmsBorRegister cmsBorRegister = new CmsBorRegister();
		cmsBorRegister.setId(request.getParameter("borId")==null?null:Long.parseLong(request.getParameter("borId")));
		cmsBorRegister.setPlanReturnTime(request.getParameter("planReturnTime")==null?null:DateTimeUtil.strToDate(request.getParameter("planReturnTime")));
		cmsBorRegister.setBorDeptDescription(request.getParameter("borDeptDescription"));
		cmsBorRegister.setBorPurpose(request.getParameter("borPurpose"));
		cmsBorRegister.setExtend1(request.getParameter("extend1"));
		String borDeptId = request.getParameter("borDeptId");
		cmsBorRegister.setBorDeptId(StringUtils.isBlank(request.getParameter("borDeptId"))?null:Long.parseLong(request.getParameter("borDeptId")));
		//当动态制定时应用
		String userName = request.getParameter("userName");
		String delegateUser = request.getParameter("delegateUser");
		try {
			//获取当前登录人的用户id（账号）
			Subject subject = SecurityUtils.getSubject();
			String username = (String) subject.getPrincipal();
			/*** 后续再进行逻辑处理 ***/
			List<UpmsUser> users = userService.findByName(username);
			UpmsUser user = new UpmsUser();
			if(users!=null&&users.size()>0){
				user = users.get(0);
			}
			Map<String, Object> variables = var.getVariableMap();
			boolean flag = (boolean)variables.get(var.getKeys());
			CmsBorAuditing cmsBorAuditing = new CmsBorAuditing();
			//修改时间
			Date now = DateTimeUtil.getNow();
			cmsBorAuditing.setCreateTime(now);
			cmsBorAuditing.setBorRegisterId(cmsBorRegister.getId());
			cmsBorAuditing.setAuditUserId((long)user.getUserId());
			cmsBorAuditing.setAuditType(Long.parseLong(taskType));
			cmsBorAuditing.setAuditUserView("重新发起检索流程");
			cmsBorAuditing.setResultType(BorrowConstant.AUDIT_RESULT_TRUE);
			cmsBorAuditing.setAuditIndex(System.currentTimeMillis()/1000);
			borRegisterService.updateByPrimaryKeySelective(cmsBorRegister);
			borAuditService.insert(cmsBorAuditing);
			//如果流程具有 指定表达式，则替换改表达式
			if(StringUtils.isNotBlank(delegateUser)){
				variables.put(delegateUser,userName);
			}
			taskService.complete(taskId, variables);
			return new CmsResult(1,"success",0);
		} catch (Exception e) {
			logger.error("error on complete task {}, variables={}", new Object[]{taskId, var.getVariableMap(), e});
			return "error";
		}
	}

	/**
	 * @author:zyp
	 * @description
	 * @date: 2019/3/29 9:06
	 * @return
	 */
	@ApiOperation(value = "获取检索登记数据")
	@RequestMapping(value = "/getSearchRegiser")
	@ResponseBody
	public Object getSearchRegister(@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
								   @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
								   @RequestParam(required = false, value = "sort") String sort,
								   @RequestParam(required = false, value = "order") String order)  {
		Object searchRegister = borRegisterService.getSearchRegister(offset, limit, sort, order);
		return  searchRegister;
	}

	public TaotaoResult selectUserIsManager(){
		TaotaoResult result = new TaotaoResult();
		Subject subject = SecurityUtils.getSubject();
		String username = (String) subject.getPrincipal();
		List<UpmsUser> user = userService.findByName(username);
		result =upmsUserRoleService.findUserRole(user.get(0).getUserId());
		return  result;
	}

	/**
	 * @author:zyp
	 * @description 查询我的检索的申请结果
	 * @date: 2019/6/17 9:59
	 * @return
	 */
	@ApiOperation(value = "查询我的检索的申请结果")
	@RequiresPermissions("cms:search:mySearch")
	@RequestMapping(value = "/mySearchData")
	@ResponseBody
	public Object mySearchData(
			@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
			@RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
			@RequestParam(required = false, value = "sort") String sort,
			@RequestParam(required = false, value = "order") String order) {
		Object result = borRegisterService.mySearchData(offset, limit, sort, order);
		return result;
	}
}